package com.zhuangwei.util;

import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zhuangwei.util.domain.ShortUrlRet;

import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 高频工具类
 *
 * @author LeviCoder
 * @create 2019-01-30 17:01
 */
public class T
{
    private static final String URL_SEPARATOR = "//";
    private static final String URL_PROTOCOL = "http";

    /**
     * 获取 UUID,32位的
     *
     * @return 返回没有“-”的 UUID
     */
    public static String UUID() {
        return RandomUtil.randomUUID().replace("-", "");
    }

    /**
     * 长地址转短地址
     *
     * @param longUrl 长地址
     * @return 长地址转化后的短地址
     */
    public static String shortURL(@NotNull String longUrl) {
        Map<String, Object> params = Maps.newHashMap();
        if (StrUtil.isEmpty(longUrl)) {
            return null;
        }
        if (!longUrl.contains(URL_SEPARATOR)) {
            longUrl = URL_PROTOCOL + ":" + URL_SEPARATOR + longUrl;
        }
        params.put("url", longUrl);
        params.put("email", "ws@parg.co");
        params.put("api_key", "4786a32f20f79a70b1ced1bf242a120e");
        String data = HttpUtil.post("https://parg.co/api/shorten", params);
        JSONObject ret = JSONUtil.parseObj(data);
        ShortUrlRet shortUrlRet = ret.toBean(ShortUrlRet.class);
        return shortUrlRet.getShort_url();
    }

    public static void main(String[] args)
    {
        /*String uuid = UUID();
        System.out.println(uuid);
        System.out.println(uuid.length());*/
        String s = shortURL("https://github.com/xkcoding/spring-boot-demo/tree/v-1.5.x");
        System.out.println(s);
    }
}
